import { shallowRef, ref } from 'vue'

import { catchFn } from '@/libs/common'
import { getPaymentItem } from './api'
import { pay } from '@/pages/pay/data'
import { update } from '../data'
import { topMessage } from '@/components/TopMessage/data'

/** 是否显示解锁 */
const showUnlockMask = ref(false)
/** 付费项设置 */
const payItem = shallowRef<T_PayItemMBTIAdvance>()
/** 当前选项 */
const selectIdx = ref(-1)
/** 支付参数 */
const payOption = {
  testType: '',
  testResultId: 0,
}
/** 倒计时 */
const countDownStr = ref('00:00')

export { showUnlockMask, payItem, selectIdx, payOption, countDownStr }

const initUnlockMask = () =>
  catchFn(async () => {
    const { data } = await getPaymentItem(payOption.testResultId)

    payItem.value = data
    selectIdx.value = -1
    showUnlockMask.value = true

    data.countDown && startCountDown(data.countDown)
  })

let tiomeout: any = null
let countDown = 0

const countTimeStr = (t: number) =>
  (countDownStr.value =
    Math.floor(t / 60)
      .toString()
      .padStart(2, '0') +
    ':' +
    (t % 60).toString().padStart(2, '0'))

const startCountDown = (time: number) => {
  countDown = time
  countTimeStr(countDown)

  tiomeout = setInterval(() => {
    countDown--
    countTimeStr(countDown)

    if (countDown <= 0) {
      clearInterval(tiomeout)
      tiomeout = null

      initUnlockMask()
    }
  }, 1000)
}

const stopCountDown = () => {
  tiomeout && clearInterval(tiomeout)
  tiomeout = null

  countDownStr.value = '00:00'
}

const confirm = async () => {
  const item = payItem.value?.itemList[selectIdx.value]

  if (!item) return

  const res = await pay({
    itemId: item.id,
    ...payOption,
  })

  if (res) {
    await update()

    topMessage.success('已' + item.itemName + '~')

    showUnlockMask.value = false
  }
}

const clear = () => {
  showUnlockMask.value = false
  payItem.value = undefined

  stopCountDown()
}

export { initUnlockMask, confirm, clear }
